1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.util.concurrent;
18
19 import com.google.caliper.BeforeExperiment;
20 import com.google.caliper.Benchmark;
21 import com.google.caliper.Param;
22
23 import java.lang.reflect.Constructor;
24 import java.util.concurrent.BlockingQueue;
25
26
27
28
29
30
31 public class MonitorBenchmark {
32
33 @Param({"10", "100", "1000"}) int capacity;
34 @Param({"Array", "Priority"}) String queueType;
35 @Param boolean useMonitor;
36
37 private BlockingQueue<String> queue;
38 private String[] strings;
39
40 @BeforeExperiment
41 @SuppressWarnings("unchecked")
42 void setUp() throws Exception {
43 String prefix =
44 (useMonitor ? "com.google.common.util.concurrent.MonitorBased" : "java.util.concurrent.");
45 String className = prefix + queueType + "BlockingQueue";
46 Constructor<?> constructor = Class.forName(className).getConstructor(int.class);
47 queue = (BlockingQueue<String>) constructor.newInstance(capacity);
48
49 strings = new String[capacity];
50 for (int i = 0; i < capacity; i++) {
51 strings[i] = String.valueOf(Math.random());
52 }
53 }
54
55 @Benchmark void addsAndRemoves(int reps) {
56 int capacity = this.capacity;
57 BlockingQueue<String> queue = this.queue;
58 String[] strings = this.strings;
59 for (int i = 0; i < reps; i++) {
60 for (int j = 0; j < capacity; j++) {
61 queue.add(strings[j]);
62 }
63 for (int j = 0; j < capacity; j++) {
64 queue.remove();
65 }
66 }
67 }
68 }